package com.teamin.service;

import com.teamin.config.ErrorCode;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import com.teamin.web.model.JwtInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * jwt服务
 *
 * @author 31484
 *
 */
@Component
public class JwtService {
	// 密匙
	@Value("${jwt.secret}")
	private String SECRET;

	// 失效时间
	@Value("${jwt.expires_in}")
	private long EXPIRES_IN;

	// token存入request header中用的字段名
	@Value("${jwt.header}")
	private String AUTH_HEADER;

	/**
	 * 生成token
	 *
	 * @param loginInfo
	 *            想要token携带的一些用户信息
	 * @return
	 */
	public String getToken(Object loginInfo) {
		return Jwts.builder().claim("loginInfo", loginInfo).setIssuedAt(new Date())
				.setExpiration(new Date(System.currentTimeMillis() + EXPIRES_IN))
				.signWith(SignatureAlgorithm.HS256, SECRET).compact();
	}

	/**
	 * 生成token信息
	 *
	 * @param loginInfo
	 *            想要token携带的一些用户信息
	 * @return
	 */
	public JwtInfo getTokenInfo(Object loginInfo) {
		String token = Jwts.builder().claim("loginInfo", loginInfo).setIssuedAt(new Date())
				.setExpiration(new Date(System.currentTimeMillis() + EXPIRES_IN))
				.signWith(SignatureAlgorithm.HS256, SECRET).compact();

		return new JwtInfo(token, AUTH_HEADER);
	}

	/**
	 * 读token
	 *
	 * @param authHeader
	 * @return
	 * @throws GlobalErrorInfoException
	 * @throws Exception
	 */
	public Claims readToken(String authHeader) throws GlobalErrorInfoException {

		try {
			Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(authHeader).getBody();
			return claims;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.UNAUTHORIZED, ErrorCode.BAD_TOKEN));
		}

	}

	/**
	 * get token存入request header中用的字段名
	 *
	 * @return
	 */
	public String getAUTH_HEADER() {
		return AUTH_HEADER;
	}

}
